<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" width="600px">
    <BasicForm @register="registerForm" />
    <template #footer>
      <a-button @click="handleSubmit(false)" type="primary" ghost>仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" >保存并关闭</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, reactive } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form"
  import * as resourceApi from "/@/api/iam/resource"
  import { instanceFormSchema } from "../data"
  const emit = defineEmits(["success", "register"])

  const isUpdate = ref(true)
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: instanceFormSchema,
    showActionButtonGroup: false,
    // mergeDynamicData: props,
    labelWidth: 120,
    wrapperCol: { lg: 24, md: 24 },
  })

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    setModalProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    await setFieldsValue({ 
      ...data.record, 
      builtInFlag: isUpdate.value ? (data.record.builtInFlag ? '1' : '0') : '0',
      hostList: isUpdate.value ? JSON.stringify(data.record.hostList) : '[]'
    })
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增" : "编辑"))

  async function handleSubmit(isClose) {
    try {
      const values = await validate()
      values.builtInFlag = values.builtInFlag === '1'
      values.hostList = !values.builtInFlag ? JSON.parse(values.hostList) : null
      setModalProps({ confirmLoading: true })
      await resourceApi.saveOrUpdateInstance(values, isUpdate.value)
      isClose && closeModal()
      emit("success")
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
